Ext.define('NF.view.farm.FeedDetails', {
    extend:'Ext.grid.Panel',
    alias:'widget.feedDetails',
    frame:true,
    feedTypesStore:null,
    activatedAtleastOnce:false,
    autoScroll:true,
    selType: 'rowmodel',

    initComponent:function(){
        var self=this;
        this.plugins = [
            Ext.create('Ext.grid.plugin.RowEditing', {
                clicksToEdit: 1
            })
        ];
        this.columns= [
            {header: 'ID',  dataIndex: 'id'},
            {header: 'Date of Feeding', dataIndex: 'dateOfFeeding', flex:1,
                editor: {xtype:'datefield',format: 'F j, Y',allowBlank:false},
                renderer: function(dateOfFeeding){
                    return Ext.util.Format.date(dateOfFeeding,'F j, Y')
                }
            },
            {header: 'Time Of Feeding', dataIndex: 'timeOfFeeding', flex:1,
                editor:{xtype:'timefield',format: 'h:i:s A',allowBlank:false},
                renderer: function(timeOfFeeding){
                    return Ext.util.Format.date(timeOfFeeding,'h:i:s A')
                }
            },
            {header: 'Quantity', dataIndex: 'quantity', flex:1,
                field:{
                    xtype:'numberfield',
                    allowBlank:false
                }
            },
            {header: 'Feed Type', dataIndex: 'feedTypeDescription', flex:1,
                field:{
                    xtype:'combobox',
                    triggerAction: 'all',
                    selectOnTab: true,
                    displayField:'feedTypeDescription',
                    valueField:'name',
                    allowBlank:false,
                    lazyRender:true,
                    store:self.prepareFeedTypesStore(),
                    queryMode:'local'
                }
            },
            {header: 'Date of Payment', dataIndex: 'dateOfPayment', flex:1,
                editor: {xtype:'datefield',format: 'F j, Y',allowBlank:false},
                renderer: function(dateOfPayment){
                    return Ext.util.Format.date(dateOfPayment,'F j, Y')
                }
            },
            {header: 'Expense', dataIndex: 'cost', flex:1,
                field:{
                    xtype:'numberfield',
                    allowBlank:false
                }
            }
        ],
        this.store = Ext.create('Ext.data.Store',{
            model:'NF.model.FeedDetails',
            autoLoad:false,
            pageSize:5,
            autoSync:false,
            proxy:{
               type:'ajax',
                url:'feed/feedDetails.json',
                reader:{
                    type:'json',
                    root:'feedDetails',
                    totalProperty:'total'
                }
            },
            listeners:{
                update:self.handleUpdate
            }
        });
        this.dockedItems = [
            {
                xtype: 'pagingtoolbar',
                store: self.store,
                dock: 'top',
                displayInfo: true,
                items:[
                    {
                        xtype:'button',
                        iconCls: 'icon-add',
                        text: 'Add Feed',
                        listeners:{
                            click:self.addNewRecord,
                            context:self.context,
                            selfer:self
                        }
                    }
                ]
            }
        ],//dockedItems
        this.callParent(arguments);
        this.setTitle("Feed Details");
        self.activatedAtleastOnce=false;
    },
    prepareFeedTypesStore:function(){
        var self=this;
        if(self.feedTypesStore == null || self.feedTypesStore == undefined){
            self.feedTypesStore = Ext.create('Ext.data.Store',{
               model:'NF.model.FeedTypes',
               autoLoad:false,
               proxy:{
                   type:'ajax',
                   url:'feed/listFeedTypes.json',
                   reader:{
                      type:'json',
                      root:'feedTypes'
                   }
               }
            });
        }
        self.feedTypesStore.load();
        return self.feedTypesStore;
    },
    handleUpdate:function(thisStore, updatedRecord, operation, options){
        Ext.Ajax.request({
            url: 'feed/updateFeedDetails.json',
            params: updatedRecord.data,
            success: function(response){
                var text = response.responseText;
                thisStore.load();
            }
        });
    },
   prepareGrid:function(){
        var self=this;
        var feedStore = self.getStore();
        feedStore.getProxy().extraParams.id = self.context.id;
        feedStore.load();
    },
    addNewRecord:function(thisButton,eventObject,contextObject){
        var self=this;
        var feedWindow = Ext.create('Ext.window.Window',{
            title:'Add Feed',
            autoHeight:true,
            width:400,
            layout:'fit',
            modal:true,
            listeners:{
                close:function(){
                    contextObject.selfer.prepareGrid();
                }
            }
        });
        feedWindow.add(contextObject.selfer.createFeedForm());
        feedWindow.show();
    },
    createFeedForm:function(){
        var self = this;
        var feedForm = Ext.create('Ext.form.Panel',{
            title:'Feed form',
            url:'feed/updateFeedDetails.json',
            bodyPadding:10,
            items:[
                {
                    xtype: 'datefield',
                    fieldLabel: 'Date of Feeding',
                    name: 'dateOfFeeding',
                    format: "c",
                    allowBlank:false,
                    value:new Date()
                },
                {
                    xtype: 'timefield',
                    fieldLabel: 'Time of Feeding',
                    name: 'timeOfFeeding',
                    format: "c",
                    allowBlank:false,
                    value:new Date()
                },
                {
                    xtype: 'numberfield',
                    fieldLabel: 'Quantity',
                    name: 'quantity',
                    allowBlank:false
                },
                {
                    xtype:'combobox',
                    triggerAction: 'all',
                    selectOnTab: true,
                    fieldLabel:'Feed Type',
                    displayField:'feedTypeDescription',
                    valueField:'name',
                    name:'feedTypeDescription',
                    allowBlank:false,
                    lazyRender:true,
                    store:self.prepareFeedTypesStore(),
                    queryMode:'local'
                },
                {
                    xtype: 'datefield',
                    fieldLabel: 'Date of Payment',
                    name: 'dateOfPayment',
                    format: "c",
                    allowBlank:false,
                    value:new Date()
                },
                {
                    xtype: 'numberfield',
                    fieldLabel: 'Cost Of Feed',
                    name: 'cost',
                    allowBlank:false
                },
                {
                    xtype: 'hiddenfield',
                    name: 'livestockId',
                    value:self.context.id,
                    allowBlank:false
                }
            ],
            buttons: [
                {
                    text: 'Submit',
                    handler: function() {
                        var self=this;
                        var form = this.up('form').getForm(); // get the basic form
                        if (form.isValid()) { // make sure the form contains valid data before submitting
                             form.submit({
                                success: function(form, action) {
                                   self.up('window').close();
                                },
                                failure: function(form, action) {
                                    Ext.Msg.alert('Failed', action.result.msg);
                                }
                             });
                        } else { // display error alert if the data is invalid
                            Ext.Msg.alert('Invalid Data', 'Please correct form errors.')
                        }
                    }
                }
            ] //buttons closed.
        });
        return feedForm;
    }
});